﻿using Microsoft.AspNetCore.SignalR;
using ORS.OrderRobot.Domain;
using ORS.OrderRobot.IOC;
using ORS.OrderRobot.Service.Helper;
using ORS.OrderRobot.ServiceContracts.Dtos.Api;
using ORS.OrderRobot.ServiceContracts.ThridPartApi;

namespace ORS.OrderRobot.Service.Jobs
{
    /// <summary>
    /// 更新商品监控记录
    /// </summary>
	public class UpdateProductLogJob : IBackgroundJob<UpdateProductLogArgs>, IScoped
    {
        private readonly IRepository<ProductMointerLog, int> _repository;
        private readonly IThirdProductService _thirdProductService;
        private readonly IHubContext<MessageHub> _hubContext;
        public UpdateProductLogJob(
            IRepository<ProductMointerLog, int> repository,
            IThirdProductService thirdProductService,
            IHubContext<MessageHub> hubContext
        )
		{
            _repository = repository;
            _thirdProductService = thirdProductService;
            _hubContext = hubContext;

        }

        public async Task ExecuteAsync(UpdateProductLogArgs args)
        {
            var nowTime = args.CreateTime;
            var existEntity = await _repository.GetAsync(x => x.ProductId == args.ProductId);
            //如果已经存在，并且最后更新日期是今天，不再写入
            if (existEntity!=null && existEntity.UpdateTime.Date == nowTime.Date)
            {
                await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = args.ProductName, Action = $"今日已存在快照,不再保存" });
                return;
            }
            var responseText = await _thirdProductService.GetProductDetail(args.ProductId);
            if (string.IsNullOrEmpty(responseText)) return;

            var fileName = $"{args.ProductId}-{nowTime.ToString("yyyyMMdd")}.json";
            //存储到本地文件
            await FileHelper.SaveTextFileAsync($"product-log/{fileName}", responseText);

            var product = System.Text.Json.JsonSerializer.Deserialize<ProductDetailResDto>(responseText);
            if(existEntity == null)
            {
                var entity = new ProductMointerLog
                {
                    CreateTime = nowTime,
                    UpdateTime = nowTime,
                    ProductId = args.ProductId,
                    ProductName = product?.name ?? "未能解析",
                    Price = product?.price ?? 0m,
                    Feature = fileName
                };
                await _repository.InsertAsync(entity);
            }
            else
            {
                existEntity.UpdateTime = nowTime;
                existEntity.ProductName = product?.name ?? "未能解析";
                existEntity.Price = product?.price ?? 0m;
                existEntity.Feature = fileName;
                await _repository.UpdateAsync(existEntity);
            }
            await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = args.ProductName, Action = $"快照已完成保存" });
        }
    }
}

